import os
import re

from lxml import etree

from PageObjectRequests import base_url
from util import http_utils
from util.DataQuery.hzflowOperation import hzflowOperation
from util.pdfSplit.compress_pdf import CompressPdf
from util.pdfSplit.pdf_split import get_file_oss
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g
from util.sys_dict import techSource


class WritePSForm():
    form_btn_loc = (By.LINK_TEXT, '上年度高新技术产品（服务）情况表')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")

    def __init__(self, driver=None):
        self.driver = driver
        self.size = 2
        self.flag = False
        setattr(g, self.class_name, list())

    @property
    def class_name(self):
        return self.__class__.__name__

    @FormDataDecorator
    def main(self, ps_id='', ps_name='', tech_fieldname='', tech_fieldlist="", tech_source='', sales_revenue='',
             is_major=1, ipr_ids='', ipn_ids='', keytech_ind='', caosp='', aipr_tsp='', oss_path=None):
        try:
            class_name = self.class_name
            li_list = getattr(g, class_name)
            if not self.flag:
                # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc, time=6)
                detail_url = ele.get_attribute("href")
                BM.get_cookie(driver=self.driver)
                if not g.all_optimized:
                    BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
                detail_url = detail_url if detail_url.startswith("https://") else \
                    base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            # if self.flag if g.repetition else False:
            if not self.flag:
                # TODO 获取已上传产品服务记录
                res = None
                text = None
                self.flag = True
                while True:
                    if not res:
                        res = http_utils.send_get(detail_url, driver=self.driver)
                    text = res.get("text")
                    # 替换掉国网随机插入的字符串
                    random_insert_chars_p = ".*?([\r\n].[0-9a-zA-Z]{4,}[\r\n].).*?"
                    res = re.findall(random_insert_chars_p, text, re.S)
                    for i in res:
                        text = text.replace(i, "")
                    tree = etree.HTML(text)
                    # 获取已上传记录
                    tr_list = tree.xpath(
                        '//form[@id="DataEprProduct_list"]//div[@class="tableRegionDivBody"]//tbody/tr')
                    for tr in tr_list:
                        ps_id_str = BM.get_first(tr.xpath("./td[2]/text()"))
                        ps_name_str = BM.get_first(tr.xpath("./td[3]/text()"))
                        sign_str = "{}:{}".format(ps_id_str, ps_name_str)
                        # print(sign_str)
                        li_list.append(sign_str)

                    # 匹配下一页 url
                    next_list = tree.xpath("//form[@id='DataEprProduct_list']//div[@class='page']/ul/li[4]/a")
                    next_a = BM.get_first(next_list)
                    next_onclick = None if not next_a else next_a.attrib.get("onclick")
                    if not next_onclick:
                        break
                    else:
                        # 获取下一页url
                        next_url_pattern = """.*?setAttribute\(['|"]action['|"],'(.*?)'.*?"""
                        next_res = re.findall(next_url_pattern, next_onclick, re.S)
                        next_url = BM.get_first(next_res)
                        next_page_pattern = """.*?value=['|"](\d+)['|"];.*?"""
                        next_page_res = re.findall(next_page_pattern, next_onclick, re.S)
                        next_page = BM.get_first(next_page_res)
                        if not next_url or not next_page:
                            break
                        next_url = (base_url + next_url) if not next_url.startswith("https://") else next_url
                        query_data = {
                            "ec_i": "",
                            "DataEprProduct_list_crd": "10",
                            "DataEprProduct_list_p": next_page,
                            "DataEprProduct_list_a_dataEprProduct_pbh": "",
                            "DataEprProduct_list_a_dataEprProduct_pcpmc": "",
                            "DataEprProduct_list_a_dataEprProduct_mainDomain": "",
                            "DataEprProduct_list_a_dataEprProduct_pjslyQkText": "",
                            "DataEprProduct_list_a_dataEprProduct_psnxssr": "",
                            "DataEprProduct_list_a_dataEprProduct_psfzycpstatus": "",
                            "DataEprProduct_list_a_dataEprProduct_pzscqbh": "",
                            "dataInnocomId": "",
                            "type": "",
                            "DataEprProduct_list_rd": "10"
                        }
                        pbh_pattern = '.*?"DataEprProduct_list_a_dataEprProduct_pbh".*?value="(.*?)".*?'
                        pbh_res = re.findall(pbh_pattern, text, re.S)
                        query_data["DataEprProduct_list_a_dataEprProduct_pbh"] = "".join(pbh_res)
                        pcpmc_pattern = '.*?"DataEprProduct_list_a_dataEprProduct_pcpmc".*?value="(.*?)".*?'
                        pcpmc_res = re.findall(pcpmc_pattern, text, re.S)
                        query_data["DataEprProduct_list_a_dataEprProduct_pcpmc"] = "".join(pcpmc_res)
                        mainDomain_pattern = '.*?"DataEprProduct_list_a_dataEprProduct_mainDomain".*?value="(.*?)".*?'
                        mainDomain_res = re.findall(mainDomain_pattern, text, re.S)
                        query_data["DataEprProduct_list_a_dataEprProduct_mainDomain"] = "".join(mainDomain_res)
                        pjslyQkText_pattern = '.*?"DataEprProduct_list_a_dataEprProduct_pjslyQkText".*?value="(.*?)".*?'
                        pjslyQkText_res = re.findall(pjslyQkText_pattern, text, re.S)
                        query_data["DataEprProduct_list_a_dataEprProduct_pjslyQkText"] = "".join(pjslyQkText_res)
                        psnxssr_pattern = '.*?"DataEprProduct_list_a_dataEprProduct_psnxssr".*?value="(.*?)".*?'
                        psnxssr_res = re.findall(psnxssr_pattern, text, re.S)
                        query_data["DataEprProduct_list_a_dataEprProduct_psnxssr"] = "".join(psnxssr_res)
                        psfzycpstatus_pattern = '.*?"DataEprProduct_list_a_dataEprProduct_psfzycpstatus".*?value="(.*?)".*?'
                        psfzycpstatus_res = re.findall(psfzycpstatus_pattern, text, re.S)
                        query_data["DataEprProduct_list_a_dataEprProduct_psfzycpstatus"] = "".join(psfzycpstatus_res)
                        pzscqbh_pattern = '.*?"DataEprProduct_list_a_dataEprProduct_pzscqbh".*?value="(.*?)".*?'
                        pzscqbh_res = re.findall(pzscqbh_pattern, text, re.S)
                        query_data["DataEprProduct_list_a_dataEprProduct_pzscqbh"] = "".join(pzscqbh_res)
                        dataInnocomId_pattern = '.*?"dataInnocomId".*?value="(.*?)".*?'
                        dataInnocomId_res = re.findall(dataInnocomId_pattern, text, re.S)
                        query_data["dataInnocomId"] = "".join(dataInnocomId_res)
                        type_pattern = '.*?"type".*?value="(.*?)".*?'
                        type_res = re.findall(type_pattern, text, re.S)
                        query_data["type"] = "".join(type_res)
                        res = http_utils.send_post(next_url, data=query_data, driver=self.driver)

            ps_id = str(ps_id).zfill(2)
            sign = "{}:{}".format("PS" + ps_id, ps_name)
            if sign in li_list:
                g.logger.info("{} 已存在".format(sign))
                return
            # 获取产品服务新增页面
            add_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/addOrUpdateDataEprProduct.do"
            BM.get_cookie(driver=self.driver)
            add_res = http_utils.send_post(url=add_url, driver=self.driver)
            token = add_res.get("token")
            text = add_res.get("text")

            save_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEprProduct.do"
            data = {
                "dataEprProduct.id": "",
                "dataInnocom.id": "",
                "dataEprProduct.dataId": "",
                "dataEprProduct.entId": "",
                "dataEprProduct.createDate": "",
                "struts.token.name": "token",
                "token": token,
                "dataEprProduct.Pbh": ps_id,
                "dataEprProduct.Pcpmc": ps_name,
                "dataEprProduct.PjslyQk": techSource.get(tech_source),
                "dataEprProduct.Psnxssr": sales_revenue,
                "dataEprProduct.Psfzycpstatus": str(is_major),
                # key 相同的 参数可以使用列表传递
                "dataEprProduct.Pzscqbh": ",".join([]),
                "__multiselect_dataEprProduct.Pzscqbh":"" ,
                "dataEprProduct.Pgjjszb": keytech_ind,
                "dataEprProduct.Pjzys": caosp,
                "dataEprProduct.Pzscqqk": aipr_tsp
                # 附件
                # "upload: (binary)"
            }
            # 获取技术领域
            domain_dict = hzflowOperation.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
            data["dataEprProduct.MainDomain1"] = domain_dict.get("domain1")
            data["dataEprProduct.MainDomain2"] = domain_dict.get("domain2")
            data["dataEprProduct.MainDomain3"] = domain_dict.get("domain3")
            value = []
            if ipr_ids:
                # 先从数据库里面查一下 ipr_ids 对应的 ip 是不是都有
                ipr_sql = """
                select * from hitech.ent_res_ipr where co_id={} and year={} and ipr_id in ({})
                """.format(g.co_id, g.year, ipr_ids)
                ps_data = DbTools.get_hitech_record_by_sql(ipr_sql, model="all")
                ipr_ids = ",".join([str(i.get("ipr_id")) for i in ps_data])
                for i in ipr_ids.split(","):
                    if i == "":
                        continue
                    if i == "0":
                        continue
                    if i.isdigit():
                        value.append("IP" + i.zfill(2))
            if ipn_ids:
                ipn_sql = """
                select * from hitech.ent_res_ipn where co_id={} and year={} and ipr_id in ({})
                """.format(g.co_id, g.year, ipn_ids)
                ipn_data = DbTools.get_hitech_record_by_sql(ipn_sql, model="all")
                ipn_ids = ",".join([str(i.get("ipr_id")) for i in ipn_data])
                for n in ipn_ids.split(","):
                    if n == "":
                        continue
                    if n == "0":
                        continue
                    if n.isdigit():
                        nstr = "NIP" + n.zfill(2)
                        value.append(nstr)
            data["dataEprProduct.Pzscqbh"] = ",".join(value)

            # 获取页面参数
            dataEprProduct_id_pattern = '.*?"dataEprProduct.id".*?value="(.*?)".*?'
            dataEprProduct_id_res = re.findall(dataEprProduct_id_pattern, text, re.S)
            data["dataEprProduct.id"] = "".join(dataEprProduct_id_res)
            dataInnocom_id_pattern = '.*?"dataInnocom.id".*?value="(.*?)".*?'
            dataInnocom_id_res = re.findall(dataInnocom_id_pattern, text, re.S)
            data["dataInnocom.id"] = "".join(dataInnocom_id_res)
            dataEprProduct_dataId_pattern = '.*?"dataEprProduct.dataId".*?value="(.*?)".*?'
            dataEprProduct_dataId_res = re.findall(dataEprProduct_dataId_pattern, text, re.S)
            data["dataEprProduct.dataId"] = "".join(dataEprProduct_dataId_res)
            dataEprProduct_entId_pattern = '.*?"dataEprProduct.entId".*?value="(.*?)".*?'
            dataEprProduct_entId_res = re.findall(dataEprProduct_entId_pattern, text, re.S)
            data["dataEprProduct.entId"] = "".join(dataEprProduct_entId_res)
            dataEprProduct_createDate_pattern = '.*?"dataEprProduct.createDate".*?value="(.*?)".*?'
            dataEprProduct_createDate_res = re.findall(dataEprProduct_createDate_pattern, text, re.S)
            data["dataEprProduct.createDate"] = BM.get_first(dataEprProduct_createDate_res)
            mdp_pattern = '.*?"__multiselect_dataEprProduct.Pzscqbh".*?value="(.*?)".*?'
            mdp_res = re.findall(mdp_pattern, text, re.S)
            data["__multiselect_dataEprProduct.Pzscqbh"] = "".join(mdp_res)

            file_path = None
            if g.need_file:
                if oss_path:
                    file_path = BM.get_material_path() + "\\PS\\ps_{}.pdf".format(ps_id)
                    is_exist = BM.check_file(file_path=file_path, size=self.size)
                    if is_exist is False:
                        oss_file = get_file_oss(oss_path=oss_path, local_path=file_path + ".pdf")
                        BM.wait_file(file_path=oss_file)
                        CompressPdf(file_path=oss_file, max_size=self.size).compress()
                        BM.wait_file(file_path=file_path)

            res = http_utils.send_post(url=save_url, data=data, file_path=file_path,
                                       file_key="upload", driver=self.driver)
            text = res.get("text")
            message = res.get("message")
            g.logger.info("上年度高新技术产品（服务）情况表（{}）上传结果: {}".format(sign, message))
            if u"成功" in message:
                li_list.append(sign)
            else:
                if u"未登录或登录超时" in text:
                    self.driver.quit()
                    os._exit(0)
                g.logger.info("text: {}".format(text))

        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(err,
                                                        err.__traceback__.tb_frame.f_globals[
                                                            "__file__"],
                                                        err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)

